import 'dart:io';

import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:xim/common/get_style_view.dart';
import 'package:xim/config/route_config.dart';
import 'package:xim/config/store_config.dart';
import 'package:xim/screen/login_screen/register_page/register_page_controller.dart';
import 'register_page_style.dart';

/// 注册页面
class RegisterPage extends GetStyleControllerView<void, RegisterPageController, RegisterPageStyle>  {

  RegisterPage({Key? key}) : super(key: key);
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  Widget buildView(BuildContext context, void data) {
    return PopScope(
      canPop: false,
      onPopInvoked: (e){
        if(e){
          return;
        }else{
          // 拦截返回
          if(controller.activeStep<1){
            Routers.back();
          }else{
            controller.updateActiveStep(controller.activeStep-1);
          }
        }
      },
      child: Scaffold(
        appBar: style.appBar,
        body: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            // 步骤控件
            style.stepper(controller.activeStep),
            const SizedBox(height: 18,),
            // 步骤页面
            Expanded(
              child: PageView(
                // physics: const NeverScrollableScrollPhysics(),
                controller: controller.pageController,
                children: [page1, page2, page3],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget get page1 =>  style.pageBuilder(
      title: "创建应用密码",
      tips: "此密码为应用密码，仅用于解锁当前设备上的此应用，且不会进行网络传输",
      child: Column (
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 密码输入表单
          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Form(
                key: _formKey,
                child: Column(
                  children: [
                    style.pwdInput(
                      onChanged: (e)=>controller.updatePassword1(e ?? ""),
                      validator: (value){
                        if(value==null || value.isEmpty){
                          return '密码不能为空';
                        }
                        if(controller.password2!=value){
                          return '两次密码不一致';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 16,),
                    style.ackPwdInput(
                      onChanged: (e)=>controller.updatePassword2(e ?? ""),
                      validator: (value){
                        if(value==null || value.isEmpty){
                          return '密码不能为空';
                        }else if(controller.password1!=value){
                          return '两次密码不一致';
                        }
                        return null;
                      },
                    ),
                  ],
                ),
              ),
              if(!style.isFocus) Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  style.usingFingerprintSelectBox(
                      isUserFingerprint: controller.isUserFingerprint,
                      onChanged: controller.updateUserFingerprintStatus
                  ),
                  style.readNoteSelectBox(
                      isReadMe: controller.isReadMe,
                      onChanged: controller.updateIsReadMe
                  ),
                ],
              ),
            ],
          ),
          if(!style.isFocus) Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              GestureDetector(
                onTap: () async {
                  if(_formKey.currentState?.validate() ?? true) {
                    _formKey.currentState?.save();
                    await StoreApi.instance.secureStoreAppPassword(controller.password1);
                    controller.updateActiveStep(1);
                  }
                },
                child: style.createPwdBtn(
                    bgColor: controller.validCheckPassword()
                        ? null
                        : Colors.blue.shade200
                ),
              ),
              const SizedBox(height: 8,)
            ],
          )
          // const SizedBox(height: 0)
        ],
      )
  );

  Widget get page2 {
    if(controller.activeStep != 1) {
      return const SizedBox();
    }
    if(controller.createAccountStatus==AccountCreateStatus.notCreate){
      EasyLoading.show(status: 'loading...', maskType: EasyLoadingMaskType.black,).then((value){
        // controller.createAccount();
        EasyLoading.dismiss();
        controller.updateAccountCreateStatus(AccountCreateStatus.hasCreate);
      });
    }
    if(controller.createAccountStatus==AccountCreateStatus.hasCreate){
      return showMnemonicTipsCreatePage2;
    }
    if(controller.createAccountStatus==AccountCreateStatus.showMnemonic){
      return showMnemonicTipsCreatePage2;
    }
    if(controller.createAccountStatus==AccountCreateStatus.hasShowMnemonic){
      return showMnemonicCreatePage2;
    }
    if(controller.createAccountStatus==AccountCreateStatus.hasReCheckMnemonic){
      return showMnemonicCreatePage2;
    }
    return Container();
  }

  Widget get hasCreatePage2 => style.pageBuilder(
    title: "保护您的账号安全",
    tips: "",
    child: Expanded(
      child: Builder(
          builder: (context) {
            var fs = 14.0;
            if(controller.activeStep==1 && controller.createAccountStatus==AccountCreateStatus.hasCreate){
              return Column(
                children: [
                  Text.rich(TextSpan(
                      text: "不要冒丢失账号的风险。",
                      style: TextStyle(fontSize: fs, color: style.textColor.color),
                      children: [
                        TextSpan(
                          text: "在信任的地点保存您的 ",
                          style: TextStyle(fontSize: fs, color: style.textColor.color),
                        ),
                        TextSpan(
                          text: "私钥助记词",
                          style: TextStyle(fontSize: fs, color: const Color(0xff00aeec)),
                        ),
                        TextSpan(
                          text: ",以此保护你的账号。",
                          style: TextStyle(fontSize: fs, color: style.textColor.color),
                        ),
                        TextSpan(
                          text: "如果你更换了新设备或重置了该应用，这是你将是您登录该应用的唯一途径",
                          style: TextStyle(fontSize: fs, color: style.textColor.color, fontWeight: FontWeight.w500),
                        )
                      ]
                  )),
                  Expanded(child: Container()),
                  GestureDetector(
                      onTap: (){
                       controller.updateAccountCreateStatus(AccountCreateStatus.showMnemonic);
                      },
                      child: style.protectAccountStartBtn
                  ),
                  const SizedBox(height: 10,),
                  Center(
                    child: Text('强烈建议', style: TextStyle(fontSize: 12, color: style.weakTextColor.color),),
                  ),
                  const SizedBox(height: 18,),
                ],
              );
            }else{
              return Container();
            }
          }
      ),
    ),
  );

  Widget get showMnemonicTipsCreatePage2 => style.pageBuilder(
    title: "保护您的账号安全",
    tips: "备份您的私钥助记词",
    child: Expanded(
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("在一张纸写下您的私钥助记词并将其存放在安全的地方"),
            const SizedBox(height: 8,),
            Text("风险与提示:"),
            Text("1.您将失去对账号的控制权"),
            Text("2.我们无法帮助您找回助记词"),
            Text("3.助记词无法更改"),
            Expanded(child: Container()),
            Center(
              child: GestureDetector(
                  onTap: (){
                    controller.updateAccountCreateStatus(AccountCreateStatus.hasShowMnemonic);
                  },
                  child: style.protectAccountStartBtn
              ),
            ),
            const SizedBox(height: 12,)
          ],
        ),
      ),
    ),
  );

  Widget get showMnemonicCreatePage2 =>  style.pageBuilder(
    title: "写下您的私钥助记词",
    tips: "这是您的私钥助记词。将它写在纸上并存放在安全的地方。您将需要在下一步中重新输入此私钥助记词，来确认的助记词是否抄写正确。",
    child: !controller.showMnemonicStatus ? Column(
      children: [
        Container(
          padding: const EdgeInsets.all(18),
          decoration: const BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.all(Radius.circular(6)),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const SizedBox(height: 10,),
              const Text("点击显示私钥助记词", style: TextStyle(
                fontWeight: FontWeight.w600,
                color: Colors.white,
                fontSize: 18),
              ),
              const SizedBox(height: 6,),
              const Text("确保没有人在看您的屏幕", style: TextStyle(color: Colors.white,fontSize: 12),),
              const SizedBox(height: 28,),
              GestureDetector(
                onTap: ()=>controller.updateShowMnemonicStatus(true),
                child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 8,horizontal: 16),
                  decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(50)),
                    border: Border.all(color: Colors.white)
                  ),
                  child: const Center(
                    child: Text("查看", style:TextStyle(fontWeight: FontWeight.w600, color: Colors.white)),
                  ),
                ),
              )
            ],
          ),
        ),
        // Expanded(child: Container()),
      ],
    ): Column(
      children: [
        Container(
          padding: const EdgeInsets.all(18),
          decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(6)),
            border: Border.all(color: Colors.grey.shade400)
          ),
          child: mnemonicGrid(showIndex: true, width: 96),
        ),
        Expanded(child: Container()),
        GestureDetector(
            onTap: ()=>controller.updateActiveStep(2),
            child: style.btn("继续")
        ),
        const SizedBox(height: 8,)
      ],
    ),
  );

  Widget get page3 => style.pageBuilder(
    title: "确认私钥助记词",
    tips: "按照之前呈现的顺序选择每个字词",
    child: Column(
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 18),
          decoration: BoxDecoration(
              borderRadius: const BorderRadius.all(Radius.circular(6)),
              border: Border.all(
                  color: controller.isFullCheckMnemonic()
                      && !controller.validCheckMnemonic()
                      ? Colors.red
                      : Colors.grey
              )
          ),
          child: GridView.count(
            shrinkWrap: true,
            crossAxisCount: 2,
            childAspectRatio: 6,
            mainAxisSpacing: 8,
            crossAxisSpacing: 16,
            children: List.generate(controller.mnemonic.length, (index) {
              var e = controller.checkMnemonic[index];
              return Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("${index+1}."),
                  const SizedBox(width: 4,),
                  GestureDetector(
                    onTap:()=>controller.deleteCheckMnemonic(index),
                    child: DottedBorder(
                      borderType: BorderType.RRect,
                      strokeCap:StrokeCap.round,
                      dashPattern: const [3,3,3,3],
                      radius: const Radius.circular(18),
                      child: Center(
                        child: SizedBox(
                          width: 82,
                          child: e.isEmpty
                              ? Container()
                              : Text(e, textAlign: TextAlign.center, style: const TextStyle(fontSize: 16),),
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }),
          ),
        ),
        const SizedBox(height: 8,),
        // check
        mnemonicGrid(
          crossAxisCount: 3,
          gridColor: (e)=>controller.isCheckedMnemonic(e) ? Colors.grey : null,
          onClick: controller.updateCheckMnemonic
        ),
        Expanded(child: Container()),
        GestureDetector(
            onTap: () async {
              if(controller.validCheckMnemonic()){
               await StoreApi.instance.storeUserCheckMnemonic(true);
                Routers.toHome();
              }
            },
            child: style.btn(
              "继续",
              bgColor: controller.validCheckMnemonic()?null:Colors.blue.shade200,
              textColor: controller.validCheckMnemonic()?null:Colors.white60
            )
        ),
        const SizedBox(height: 8,),
      ],
    ),
  );

  /// 助记词
  Widget mnemonicGrid({
    int crossAxisCount=2,
    bool showIndex = false,
    double width=76,
    Color? Function(String)? gridColor,
    void Function(String)? onClick}) => GridView.count(
      shrinkWrap: true,
      crossAxisCount: crossAxisCount,
      childAspectRatio: 3.0,
      children: List.generate(controller.mnemonic.length, (index) {
        var e = controller.shuffleMnemonic[index];
        return GestureDetector(
          onTap: ()=>onClick?.call(e),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 4,vertical: 2),
            child: Center(
              child: Container(
                width: width,
                padding: const EdgeInsets.symmetric(vertical: 2,horizontal: 6),
                decoration: BoxDecoration(
                    color: gridColor?.call(e),
                    border: Border.all(style: BorderStyle.solid),
                    borderRadius: const BorderRadius.all(Radius.circular(6))
                ),
                child: Text("${showIndex?("${index+1}" ". "):''}$e", textAlign: TextAlign.center,),
                // child: Container(),
              ),
            ),
          ),
        );
      }),
    );

}
